package biz

import (
	amount1RPC "amount1_server/api/Amount1Server/v1"
	v1 "app_server/api/helloworld/v1"
	"context"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/trace"

	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/log"
)

var (
	// ErrUserNotFound is user not found.
	ErrUserNotFound = errors.NotFound(v1.ErrorReason_USER_NOT_FOUND.String(), "user not found")
)

// Greeter is a Greeter model.
type Greeter struct {
	Hello string
}

// GreeterRepo is a Greater repo.
type GreeterRepo interface {
	Save(context.Context, *Greeter) (*Greeter, error)
}

// GreeterUsecase is a Greeter usecase.
type GreeterUsecase struct {
	repo GreeterRepo
	log  *log.Helper
	// Notice 需要加上被调用服务的RPC Client
	amount1Client amount1RPC.Amount1ServiceClient
}

// NewGreeterUsecase new a Greeter usecase.
func NewGreeterUsecase(repo GreeterRepo, logger log.Logger, amount1Cli amount1RPC.Amount1ServiceClient) *GreeterUsecase {
	return &GreeterUsecase{
		repo:          repo,
		log:           log.NewHelper(logger),
		amount1Client: amount1Cli,
	}
}

func (uc *GreeterUsecase) HandleAmounts(ctx context.Context, req *v1.HandleAmountsRequest) (*v1.Empty, error) {
	// Notice biz层与data层
	ctx, span := otel.Tracer("BIZ").Start(ctx, "HandleAmountsBiz", trace.WithSpanKind(trace.SpanKindInternal))
	defer span.End()

	reply := v1.Empty{}

	// 调用amount1的RPC接口
	amount1TransOutOrderReq := amount1RPC.TransOutOrderRequest{
		Id:          req.Id,
		OrderNo:     req.OrderNo,
		StockChange: req.Amount,
	}
	_, errAmount1TransOut := uc.amount1Client.TransOutOrder(ctx, &amount1TransOutOrderReq)
	if errAmount1TransOut != nil {
		return nil, errAmount1TransOut
	}

	return &reply, nil
}
